package com.dept.controller;

import com.common.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Str
 * @Date 2022/1/6 15:56
 * @Description :
 */
@RequestMapping("/deptCaller")
@RestController
@EnableDiscoveryClient
public class DeptCallerController {
    @Autowired
    private RestTemplate restTemplate;

    // 服务发现的客户端
    @Autowired
    private DiscoveryClient client;

    // 这是在eureka中的服务名称
    private final String DEPT_SERVICE_NAME = "DEPT-PROVIDER";

    // localhost:9201/deptCaller/getDeptById?id=1
    @GetMapping("/getDeptById")
    public String getDeptById(@RequestParam("id") Integer id){
        // 格式：http://服务名称
        // 使用注册中心的区别就是不用再打IP地址和端口
        String url="http://"+DEPT_SERVICE_NAME+"/dept/getDeptById?id={0}";
        Dept dept = restTemplate.getForObject(url, Dept.class, id);
        System.out.println("port："+dept.getDeptDesc());
        return "<br/>COME FROM dept-provider：<br/>"+dept;
    }

    /**
     * localhost:9201/deptCaller/getServiceList
     * @return java.lang.String
     */
    @GetMapping("/getServiceList")
    public ArrayList<Object> getServiceList(){
        ArrayList<Object> list = new ArrayList<>();

        // 获取所有服务名称列表
        List<String> services = client.getServices();
        for (String service : services) {
            // 根据服务名称获取一个服务的详细列表
            List<ServiceInstance> instances = client.getInstances(service);
            list.add(instances);
        }

        return list;
    }
}
